import sha, time


class Session:
    def start(self, cookie, req_ctx):
        self.stores = {}
        self.cookie = cookie
        #fetch sid or build sid
        if req_ctx.get_params.get('sid'):
            sid = str(req_ctx.get_params.get('sid'))
        elif cookie.get('sid') == None:
            sid = sha.new(repr(time.time())).hexdigest()
            cfg = self.cfg
            domain = cfg.get('cookie', 'domain')
            cookie.put_cookie('sid', sid, domain)
        else:
            sid = cookie.get_cookie('sid')
        #print 'sid', sid
        self.sid = sid
        #build session
        self.build_session()
    def getId(self):
        return self.sid    
    def config(self, cfg):
        pass
    
    def build_session(self):  
        pass
    def commit(self):
        pass
    
    def save(self, key, value):
        self.stores[key] = value
    
    def delete(self, key):
        if self.stores.has_key(key):
            del self.stores[key]
    
    def get(self, key):
        return self.stores.get(key)
    
    def get_default(self, key, default):
        value = self.stores.get(key)
        return value and value or default
        
    def __getitem__(self, key):
        return self.stores.get(key)
    
    def items(self):
        return self.stores.items()